/**
 * @Title:  MainActivity.java 
 * @Copyright:  XXX Co., Ltd. Copyright YYYY-YYYY,  All rights reserved 
 * @Description:  TODO<请描述此文件是做什么的> 
 * @author:  MeiYi 
 * @data:  2016-2-23 下午5:12:01 
 * @version:  V1.0 
 */

package artid.com.arttogoa;
import org.apache.commons.lang3.StringUtils;
import artid.com.arttogoa.app.ArtWorkApp;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.parser.ArtistWorkInfoParse;
import artid.com.arttogoa.parser.AuthcertificationItem;
import artid.com.arttogoa.parser.UpdataSystemMessageParser;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.BitmapUtil;
import artid.com.arttogoa.util.MD5;
import artid.com.arttogoa.util.MySharedPreferences;
import artid.com.arttogoa.util.ToastUtil;
import artid.com.arttogoa.util.VeDate;
import artid.com.arttogoa.volley.BitmapCache;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.Volley;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * TODO<实名认证-审核 >
 * 
 * @author 熊彬
 * @data: 2016-2-23 下午5:12:01
 * @version: V1.0
 */
public class RealNameAuthenticationTwoActivity extends BaseActivity implements
OnClickListener {
	private Intent in;
	private LinearLayout authIng, authFail, authOk, fail, succ;
	private ImageView authImg, authPer;
	private RelativeLayout auth_im_layout;
	private Button btn_real_next;
	int type;
	private TextView finish_time,realname, realid, authtime, fauthtime, reason;
	private ImageLoader mImageLoader;
	private Boolean isRegister=false;//是否是从注册过来的（默认false）
	private String pushMessageID;//推送消息的ID

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.example.artworkarta.BaseActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_real_name_authentication_two);
		ArtWorkApp.getInstance().addActivity(this);
		setContent(this, getIntent());
		initData();
	}

	/**
	 * 
	 */
	private void initData() {
		mTittle = (TextView) findViewById(R.id.title_text);
		mTittle.setText("实名认证");
		setBack();
		// 注册当前广播
		IntentFilter filter = new IntentFilter("com.RealNameAuthenticationTwoActivity.receiver");
		registerReceiver(broadcastReceiver, filter);
		isRegister=getIntent().getBooleanExtra("isRegister", false);
		RequestQueue mQueue = Volley.newRequestQueue(mContext);
		mImageLoader = new ImageLoader(mQueue, new BitmapCache());
		authIng = (LinearLayout) findViewById(R.id.RealNameAuthenticationTwo_ll_auth_ing);
		authFail = (LinearLayout) findViewById(R.id.RealNameAuthenticationTwo_ll_auth_fail);
		authOk = (LinearLayout) findViewById(R.id.RealNameAuthenticationTwo_ll_auth_ok);
		succ = (LinearLayout) findViewById(R.id.RealNameAuthenticationTwo_auth_succ);
		fail = (LinearLayout) findViewById(R.id.RealNameAuthenticationTwo_auth_fail);
		authImg = (ImageView) findViewById(R.id.RealNameAuthenticationTwo_auth_im);
		authPer = (ImageView) findViewById(R.id.RealNameAuthenticationTwo_auth_im_per);
		auth_im_layout = (RelativeLayout) findViewById(R.id.RealNameAuthenticationTwo_auth_im_layout);
		btn_real_next = (Button) findViewById(R.id.RealNameAuthenticationTwo_btn_real_next);
		btn_real_next.setVisibility(View.GONE);
		finish_time = (TextView) findViewById(R.id.RealNameAuthenticationTwo_finish_time);
		realname = (TextView) findViewById(R.id.RealNameAuthenticationTwo_real_name);
		realid = (TextView) findViewById(R.id.RealNameAuthenticationTwo_real_id);
		authtime = (TextView) findViewById(R.id.RealNameAuthenticationTwo_auth_time);
		fauthtime = (TextView) findViewById(R.id.RealNameAuthenticationTwo_fauth_time);
		reason = (TextView) findViewById(R.id.RealNameAuthenticationTwo_reason);
		btn_real_next.setOnClickListener(this);
		String na = AppUtil.getUser().getPath();
		String name = MD5.getMD5(na) + na.substring(na.lastIndexOf("."));
		String path = Environment.getExternalStorageDirectory() + "/YJB/"
				+ name;
		String SharedPath = MySharedPreferences
				.getMySharedPreferences(mContext).getValue("HeadURL", "");
		// 判断本地保存的头像是否与服务器地址相同
		if (SharedPath.equals(path)) {
			Bitmap smallBitmap = BitmapUtil
					.getSmallFilletBitmap(path, 500, 500);
			if(smallBitmap!=null){
				authImg.setImageBitmap(smallBitmap);
			}else{
				downloadAndSaveHeadImage();
			}
		} else {
			downloadAndSaveHeadImage();
		}

		//判断是否是推送消息进入的
		if(getIntent().getBooleanExtra("isPush", false)==true){
			pushMessageID=getIntent().getStringExtra("messageID");
			requestAutoStatus(true);
		}else{
			requestAutoStatus(false);
		}
	}
	/**
	 * 获取审核信息
	 * isSetPush 主要是用来判断是否重置推送消息未读状态
	 */
	private void requestAutoStatus(final Boolean isSetPush) {
		Boolean isCloseDialog=true;//是否在加载完之后关闭加载动画(默认关闭)
		if(isSetPush==true){
			isCloseDialog=false;
		}else{
			isCloseDialog=true;
		}
		VolleyBasic.getInstance(RealNameAuthenticationTwoActivity.this).post(true,isCloseDialog,
				Cache.authcertification,
				VolleyMap.getInstance().authCertification(),
				AuthcertificationItem.class, new VolleyCallback() {
			@Override
			public void onSuccess(VolleyData vd) {
				AuthcertificationItem item = (AuthcertificationItem) vd.getData();
				String status = item.getIs_auth();
				realname.setText("真实姓名："+item.getRealname());
				// 用于显示的加*身份证
				try {
					String show_id =item.getIdentity().substring(0, 1) + "****************" + item.getIdentity().substring(17);
					realid.setText("身份证号码："+show_id);
				} catch (Exception e) {
					// TODO: handle exception
					realid.setText("身份证号码："+item.getIdentity());
				}

				long auth_time = Long.parseLong(item.getAuth_time());
				long finish_times = Long.parseLong(item.getFinish_time());
				authtime.setText("申请认证时间:"+ VeDate.formatUnixTime(auth_time));
				fauthtime.setText("申请认证时间:"+VeDate.formatUnixTime(auth_time));
				reason.setText(item.getReason());
				//获取最新的认证信息并通知主页与个人信息刷新
				AppUtil.getUser().setIs_auth(status);
				MainActivity.isRefreshPersonal=true;
				if (status.equals("0")) {
					//未认证，跳到身份证认证
					Intent in = new Intent(RealNameAuthenticationTwoActivity.this,RealNameAuthenticationActivity.class);
					startActivity(in);
					finish();
				} else if (status.equals("1")) {
					//已认证
					authIng.setVisibility(View.GONE);
					authOk.setVisibility(View.VISIBLE);
					type = 1;
					btn_real_next.setText("去我的主界面");
					btn_real_next.setVisibility(View.VISIBLE);

				} else if (status.equals("2")) {
					//认证中
					authPer.setVisibility(View.GONE);
					type = 2;
					btn_real_next.setText("随便看看");
					btn_real_next.setVisibility(View.VISIBLE);
				} else if (status.equals("-1")) {
					//未通过
					type = -1;
					authIng.setVisibility(View.GONE);
					auth_im_layout.setVisibility(View.GONE);
					authFail.setVisibility(View.VISIBLE);
					fail.setVisibility(View.VISIBLE);
					succ.setVisibility(View.GONE);
					btn_real_next.setText("重新申请实名认证");
					btn_real_next.setVisibility(View.VISIBLE);
				}
				if(isSetPush==true){
					updataSystmeMessage(pushMessageID);
				}
			}
			@Override
			public void onError(VolleyError volleyError) {
			}
		});
	}

	/**
	 * 修改系统消息为已读
	 */

	private void updataSystmeMessage(String MessageId){
		VolleyBasic.getInstance(this).post(false,false,Cache.updateSystemread,
				VolleyMap.getInstance().updateSystemread(MessageId),UpdataSystemMessageParser.class,new VolleyCallback() {
			public void onSuccess(VolleyData vd) {
				// TODO Auto-generated method stub
				System.out.println(vd.getJson());
				UpdataSystemMessageParser bean=(UpdataSystemMessageParser) vd.getData();
				if("1".equals(bean.getStatus())){
					getArtistWorkInfo();
				}else if("0".equals(bean.getStatus())){
					//失败
					ToastUtil.toast(mContext, "修改消息状态失败");
				}
			}
			public void onError(VolleyError volleyError) {
			}
		});
	}


	/**
	 * 艺术家备案动态资讯数量和推送消息数量
	 */
	private void getArtistWorkInfo(){
		VolleyBasic.getInstance(this).post(false,true,Cache.artistWorkInfo,VolleyMap.getInstance().artistWorkInfo(),
				ArtistWorkInfoParse.class, new VolleyCallback() {
			@Override
			public void onSuccess(VolleyData vd) {
				Log.d("log", vd.toString());
				ArtistWorkInfoParse bean=(ArtistWorkInfoParse) vd.getData();
				if(bean!=null){
					AppUtil.getUser().setRecordnum(bean.getRecordnum());
					AppUtil.getUser().setTrendsnum(bean.getTrendsnum());
					AppUtil.getUser().setNewsnum(bean.getNewsnum());
					AppUtil.getUser().setIs_auth(bean.getIs_auth());
					MainActivity.isSystemPush=bean.getIs_pushread();
					Intent intent2 = new Intent("com.Push.receiver");  
					intent2.putExtra("UpMessageType", true);
					mContext.sendBroadcast(intent2);
				}
			}
			@Override
			public void onError(VolleyError volleyError) {

			}
		});
	}

	/**
	 * 下载并保存图片
	 */
	private void downloadAndSaveHeadImage(){
		if (!StringUtils.isEmpty(AppUtil.getUser().getAvatarurl())) {
			mImageLoader.get(AppUtil.getUser().getAvatarurl(),
					new ImageListener() {
				@Override
				public void onErrorResponse(VolleyError error) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onResponse(ImageContainer response,
						boolean isImmediate) {
					// TODO Auto-generated method stub
					try {
						Bitmap head = response.getBitmap();
						if (head != null) {
							String imgUrl = AppUtil.getUser()
									.getPath();
							// 保存头像
							String path = null;
							if (!StringUtils.isEmpty(imgUrl)) {
								String name = MD5.getMD5(imgUrl)
										+ imgUrl.substring(imgUrl
												.lastIndexOf("."));
								// 保存头像地址
								path = Environment
										.getExternalStorageDirectory()
										+ "/YJB/" + name;
								BitmapUtil.saveBitmapToFile(head,
										path);
								MySharedPreferences
								.getMySharedPreferences(
										mContext).setValue(
												"HeadURL", path);
							}
							authImg.setImageBitmap(BitmapUtil
									.toRoundCorner(head, 8));
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});
		}
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.RealNameAuthenticationTwo_btn_real_next:
			//根据审核信息进行对按钮的不同操作
			if (type==2) {
				//判断是否通过审核
				if(isRegister==true){
					in = new Intent(mContext, LoginAvtivity.class);
					startActivity(in);
					ArtWorkApp.getInstance().exit();
				}else{
					if(getIntent().getBooleanExtra("isPush", false)==true){
						//判断是否是推送消息进入的
						ArtWorkApp.getInstance().RemoveActivity("MainActivity");
						ArtWorkApp.getInstance().exit();
					}else{
						//从个人信息进入的
						Intent intent1 = new Intent("com.PersonalActivity.receiver");  
						intent1.putExtra("isCloseActivity", true);
						sendBroadcast(intent1);
						finish();
					}
				}
			} else if (type == -1) {
				//重新审核
				in = new Intent(mContext, RealNameAuthenticationActivity.class);
				startActivity(in);
				finish();
			} else if(type==1){
				if(getIntent().getBooleanExtra("isPush", false)==true){
					//判断是否是推送消息进入的
					ArtWorkApp.getInstance().RemoveActivity("MainActivity");
					ArtWorkApp.getInstance().exit();
				}else{
					//从个人信息进入的
					Intent intent1 = new Intent("com.PersonalActivity.receiver");  
					intent1.putExtra("isCloseActivity", true);
					sendBroadcast(intent1);
					finish();
				}
			}else{
				finish();
			}

			break;

		default:
			break;
		}

	}
	
	// 广播监听
		BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				// TODO Auto-generated method stub
				if (intent.getBooleanExtra("UmengPush", false) == true) {
					if("9".equals(intent.getStringExtra("PushType"))){
						//当有审核信息的时候通知刷新审核信息
						requestAutoStatus(false);
					}
				}
			}
		};
}
